import { ChangeDetectorRef, Component, Input, OnInit } from '@angular/core'
import { Router } from '@angular/router'
import { Store } from '@ngrx/store'
import { DValidateRules, FormLayout } from 'ng-devui'
import { UserAuthService } from 'src/app/@core/user-auth.service'
import { AppState } from 'src/app/store'
import { DialogService } from 'ng-devui/modal'
import { AuthGuardService } from 'src/app/@core/auth-guard-service.guard'
import { CookieService } from 'ngx-cookie-service'

@Component({
  selector: 'app-logins',
  templateUrl: './logins.component.html',
  styleUrls: ['./logins.component.scss']
})
export class LoginsComponent implements OnInit {
  layoutDirection: FormLayout = FormLayout.Vertical
  @Input() fun: any
  msgs: Array<Object> = []
  showPassword = false
  isShared = false
  wrongMsg: string;
  wrongM = false

  formData = {
    password: '',
    userName: null,
    authentiCode: ''
  }

  formRules: { [key: string]: DValidateRules } = {
    rule: {
      messageShowType: 'text',
    },
    usernameRules: {
      validators: [
        { minlength: 3 },
        { required: true, message: '账号不能为空' },
      ]
    },
    passwordRules: {
      validators: [
        { required: true, message: '密码不能为空' },
        { minlength: 8 },
        { maxlength: 32 }
      ]
    }
  }

  userInfo: any
  constructor(
    private cdr: ChangeDetectorRef,
    private userAuthService: UserAuthService,
    private router: Router,
    private store: Store<AppState>,
    private dialogService: DialogService,
    private authGuardService: AuthGuardService,
    private cookieService: CookieService
  ) { }

  ngOnInit(): void {
    this.cookieService.delete('token')
    localStorage.removeItem('userName')
    localStorage.removeItem('token')
    localStorage.removeItem('ROLE')
    localStorage.removeItem('userId')
    localStorage.removeItem('PasswordChange')
    this.userAuthService.getCurrentUser(this.formData.userName)
    this.store.dispatch({
      type: 'RESET_TODO',
      payload: {}
    })
  }

  maxUsers(num) {
    return (val) => {
      return !val || val.length <= num
    }
  }

  initial() {
    this.wrongM = false
  }

  submitForm({ valid }) {
    if (valid) {
      this.userAuthService
        .userLogIn(this.formData.userName, this.formData.password)
        .subscribe((res) => {
          if (res.code === 0) {
            this.wrongM = false
            if (this.fun) {
              this.fun()
            }
            this.showToast('success', '', '登录成功！')
            localStorage.setItem('userId', res.data.userId)
            localStorage.setItem('userName', res.data.userName)
            localStorage.setItem('ROLE', res.data.role)
            localStorage.setItem('PasswordChange', res.data.pwdChanged)
            this.userAuthService.getCurrentUser(res.data)
            if (res.data.role == 'admin' && res.data.pwdChanged == false) {
              this.openDialog(
                'warning',
                '管理员首次登录，请修改密码，否则无法进行管理操作！'
              )
              this.router.navigate(['/baseUserInfo'])
            } else {
              this.router.navigate(['/home'])
            }
            this.judgeDisabled()
            this.addMenu(res)
            this.getAvatar(res.data.userId)
          } else {
            this.wrongM = true
            this.wrongMsg = res.msg
          }
        })
    }
  }

  getAvatar(userId) {
    this.userAuthService.getAvatar(userId).subscribe((res) => {
      this.store.dispatch({
        type: 'AVATAR',
        payload: res.data.FileUrl
      })
    })
  }

  judgeDisabled() {
    this.authGuardService.getBlockChainType().subscribe((res) => {
      if (res.data.type === 'shared') {
        this.isShared = true
        this.cdr.markForCheck()
      } else {
        this.isShared = false
        localStorage.setItem('IS_SHARED', '1')
        this.store.dispatch({
          type: 'ADD_TODO',
          payload: {
            name: '区块链',
            value: '2',
            link: '/blockchain',
            img: '../../../assets/img/home/blockchain.svg'
          }
        })
        this.cdr.markForCheck()
      }
    })
  }

  addMenu(res) {
    if (res.data.role === 'admin') {
      this.store.dispatch({
        type: 'ADD_TODO',
        payload: {
          name: '管理',
          value: '4',
          link: '/manage/collection',
          img: '../../../assets/img/home/setting.svg'
        }
      })
    }
  }

  showToast(type: any, title: string, msg: string) {
    this.msgs = [{ severity: type, summary: title, detail: msg }]
  }

  config = {
    id: 'dialog-service',
    width: '360px',
    maxHeight: '200px',
    zIndex: 1050,
    backdropCloseable: true,
    html: true
  }
  openDialog(dialogtype?: string, content?: string) {
    const results = this.dialogService.open({
      ...this.config,
      content: content,
      dialogtype: dialogtype,
      buttons: [
        {
          text: '关闭',
          handler: ($event: Event) => {
            results.modalInstance.hide()
          },
          cssClass: 'primary'
        }
      ]
    })
  }

  closeDialog() {
    var url = this.router.serializeUrl(
      this.router.createUrlTree(['/register'])
    )

    if (this.fun) {
      window.open('#' + url, '_blank')
    }
    else {
      this.router.navigate([url])
    }
  }
}
